import React, { useState, useRef, useEffect } from 'react';

interface MusicPlayerProps {
  audioSrc: string;
}

const MusicPlayer: React.FC<MusicPlayerProps> = ({ audioSrc }) => {
  // 音乐播放相关状态
  const [isPlaying, setIsPlaying] = useState(false);
  const [volume, setVolume] = useState(0.5); // 音量默认值0.5 (0-1)
  const [currentTime, setCurrentTime] = useState(0); // 当前播放时间（秒）
  const [duration, setDuration] = useState(0); // 音频总时长（秒）
  const audioRef = useRef<HTMLAudioElement>(null);

  // 用户第一次点击页面后自动播放音乐
  useEffect(() => {
    const handleClick = () => {
      const audio = audioRef.current;
      if (audio && !isPlaying) {
        // 尝试播放
        const playPromise = audio.play();
        
        if (playPromise !== undefined) {
          playPromise
            .then(() => {
              // 仅在播放成功后更新状态
              setIsPlaying(true);
              console.log("自动播放成功");
            })
            .catch(err => {
              console.error("自动播放失败:", err);
              // 确保失败时状态一致
              setIsPlaying(false);
            });
        }
      }
      // 无论成功与否，都移除事件监听器
      document.removeEventListener('click', handleClick);
    };
    
    document.addEventListener('click', handleClick);
    return () => document.removeEventListener('click', handleClick);
  }, []);

  // 播放/暂停切换函数
  const toggleMusic = () => {
    const audio = audioRef.current;
    if (!audio) return;
    
    console.log("当前状态:", isPlaying, "音频暂停状态:", audio.paused);
    
    if (isPlaying) {
      // 确保音频暂停
      audio.pause();
      // 立即更新状态
      setIsPlaying(false);
      console.log("已暂停音乐");
    } else {
      // 尝试播放音频
      const playPromise = audio.play();
      
      if (playPromise !== undefined) {
        playPromise
          .then(() => {
            setIsPlaying(true);
            console.log("已开始播放音乐");
          })
          .catch(err => {
            console.error("播放失败:", err);
            // 如果播放失败，确保状态保持为未播放
            setIsPlaying(false);
          });
      }
    }
  };
  
  // 音量调节函数
  const handleVolumeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newVolume = parseFloat(e.target.value);
    if (audioRef.current) {
      audioRef.current.volume = newVolume;
      setVolume(newVolume);
    }
  };
  
  // 进度条调节函数
  const handleProgressChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newTime = parseFloat(e.target.value);
    if (audioRef.current) {
      audioRef.current.currentTime = newTime;
      setCurrentTime(newTime);
    }
  };
  
  // 格式化时间为 mm:ss
  const formatTime = (timeInSeconds: number) => {
    const minutes = Math.floor(timeInSeconds / 60);
    const seconds = Math.floor(timeInSeconds % 60);
    return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
  };

  return (
    <>
      {/* 音频元素 */}
      <audio 
        ref={audioRef} 
        src={audioSrc} 
        loop 
        onPlay={() => setIsPlaying(true)}
        onPause={() => setIsPlaying(false)}
        onTimeUpdate={(e) => setCurrentTime(e.currentTarget.currentTime)}
        onLoadedMetadata={(e) => setDuration(e.currentTarget.duration)}
        onVolumeChange={(e) => setVolume(e.currentTarget.volume)}
      />
      
      {/* 音乐控制面板 */}
      <div className="absolute top-4 right-4 bg-white bg-opacity-80 p-3 rounded-lg shadow-lg z-50 w-64">
        <div className="flex items-center justify-between mb-2">
          <button
            onClick={() => {
              console.log("按钮被点击");
              toggleMusic();
            }}
            className="bg-blue-500 hover:bg-blue-600 text-white px-4 py-1 rounded"
          >
            {isPlaying ? '⏸️ 暂停' : '▶️ 播放'}
          </button>
          
          <div className="flex items-center ml-2">
            <span className="text-xs mr-1">🔊</span>
            <input
              type="range"
              min="0"
              max="1"
              step="0.01"
              value={volume}
              onChange={handleVolumeChange}
              className="w-16"
              title={`音量: ${Math.round(volume * 100)}%`}
            />
          </div>
        </div>
        
        {/* 进度条 */}
        <div className="mt-2">
          <div className="flex justify-between text-xs mb-1">
            <span>{formatTime(currentTime)}</span>
            <span>{formatTime(duration)}</span>
          </div>
          <input
            type="range"
            min="0"
            max={duration || 100}
            step="0.1"
            value={currentTime}
            onChange={handleProgressChange}
            className="w-full"
          />
        </div>
      </div>
    </>
  );
};

export default MusicPlayer;